#! /usr/bin/env python
# -*- coding: utf-8 -*-
#  Create by Albert_Chen
#  CopyRight (py) 2016年 陈超. All rights reserved by Chao.Chen.


__author__ = 'Albert'

import requests
import pickle
import os
import json
import logging

REMOTE = 'http://114.55.117.52:5000'
API = '/cbi360/company/'

def load_pickle_data(file_path):
    print "loading data"
    fopen = open(file_path)
    data = pickle.load(fopen)
    return data

def update_elsearch_index(data):

    for datum in data:
        try:
            print datum
            cid = datum['CID']
            logging.info('Update company id %s'%cid )
            url = REMOTE + API+str(cid) +'?pretty'
            uuid = datum.get('CGUID')
            datum['CGUID'] = unicode(uuid)
            datum = json.dumps(datum)
            resp = requests.request("PUT", url, data=datum)

        except Exception,e:
            print e
            continue
            # print 'Update company file %s' %str(e)
            # continue

def main(file_path):

    if not(os.path.isfile(file_path) and file_path.endswith('.pkl')):
        print "[Err] input file is not pkl format"
        return sys.exit(-1)
    else:
        logging.info("update info")
        data = load_pickle_data(file_path)
        update_elsearch_index(data)

if __name__ == "__main__":

    import argparse
    import sys

    parser = argparse.ArgumentParser(prog="Pickle Data To ElasticSearch Engine",
                                     usage="%(prog)s [option]",
                                     description='Help me to update index doc to elastic search by using pickle data.')
    parser.add_argument('--input', dest='input', required=True,
                        help='Pickle data file address, please drag file into terminal')

    args = parser.parse_args(sys.argv[1:])

    file_path = args.input
    # print file_path
    # main(file_path)